var laytpl, form, element, repeat_flag, table;

layui.use(['form','laydate', 'laytpl', 'element'], function () {
	form = layui.form;
	repeat_flag = false; //防重复标识
	element = layui.element;
	laytpl = layui.laytpl;
	laydate = layui.laydate;

	form.render();
	refreshTable();

	//渲染时间
	laydate.render({
		elem: '#start_time'
		,type: 'datetime'
		,change: function(value, date, endDate){
			$(".date-picker-btn").removeClass("selected");
		}
	});

	laydate.render({
		elem: '#end_time'
		,type: 'datetime'
		,change: function(value, date, endDate){
			$(".date-picker-btn").removeClass("selected");
		}
	});

	// 监听工具栏操作
	table.tool(function (obj) {
		var data = obj.data;
		switch (obj.event) {
			case 'offer_price_stock':
				offerPriceStock(data.sku_id, obj);
				break;
			case 'set_area':
				setArea(data.sku_id, obj);
				break;
		}
	});

	// 搜索功能
	form.on('submit(search)', function (data) {
		table.reload({
			page: {
				curr: 1
			},
			where: data.field
		});
		return false;
	});
});

/**
 * 刷新表格列表
 */
function refreshTable() {
	var cols = [
		[{
			field: 'sku_name',
			title: '商品信息',
			unresize: 'false',
			width: '30%',
			templet: '#goods_info'
		},
		{
			field: 'sku_id',
			title: '商品SKU',
			unresize: 'false',
		},
		{
			field: 'sku_price',
			title: '当前售价',
			unresize: 'false',
			templet: function (data) {
				return '￥' + data.sku_price;
			}
		},
		{
			field: 'offer_price',
			title: '我的报价',
			unresize: 'false',
			templet: function (data) {
				return data.offer_price > 0 ? '￥' + data.offer_price : data.offer_price;
			}
		},
		{
			field: 'offer_stock',
			title: '总库存',
			unresize: 'false',
			templet: function (data) {
				return data.offer_stock;
			}
		},
		{
			field: 'update_time',
			title: '最近报价',
			unresize: 'false',
		},
		{
			title: '操作',
			toolbar: '#operation',
			unresize: 'false',
		}]
	];

	table = new Table({
		id: 'goods_list',
		elem: '#goods_list',
		url: ns.url("shop/goods/offer_goods"),
		cols: cols,
		toolbar: true,
		defaultToolbar: ['filter', 'print', 'exports'],
		limits: [10,50,100,500,1000,5000,10000,50000,100000],
		where: {
			sku_id: $("input[name='sku_id']").val(),
			search_text: $("input[name='search_text']").val(),
			category_id: $("input[name='category_id']").val(),
			stock_status: $("select[name='stock_status'] option:checked").val(),
			offer_type: $("select[name='offer_type'] option:checked").val(),
			start_time: $("input[name='start_time']").val(),
			end_time: $("input[name='end_time']").val(),
		}
	});
}

/**
 * 开始报价
 **/
function offerPriceStock(sku_id, obj){
	layer.prompt({
		formType: 0,
		title: '开始报价',
		placeholder: '请输入您的报价',
		area: ['400px', '100px'],
	}, function(value, index){
		if($('#stock').val().length === 0){
			layer.tips("请输入您的库存", $('#stock'));
			return false;
		}
		start(sku_id, value, $('#stock').val(), obj, index);
	});
	$(".layui-layer-content").append('<br/><input type="number" id="stock" class="layui-input" placeholder="请输入您的库存" />');
}

//报价数据提交
function start(sku_id, price, stock, obj, index) {
	$.ajax({
		type: "post",
		url: ns.url("shop/goods/goods_price_stock"),
		async: true,
		dataType: 'json',
		data: {sku_id: sku_id, price: price, stock: stock},
		success: function (res) {
			if (res.code == 0) {
				layer.close(index);
				obj.update({
					sku_price: res.data.average_price,
					offer_price: res.data.price,
					offer_stock: res.data.stock,
					update_time: res.data.update_time,
				});
				layer.msg(res.message, {time: 1500, icon: 1});
				return false;
			}
			layer.msg(res.message, {time: 1500, icon: 2});
		}
	});
}

/**
 * 七天时间
 */
function datePick(date_num,event_obj){
	$(".date-picker-btn").removeClass("selected");
	$(event_obj).addClass('selected');
	// alert(new Date().format("yyyy-MM-dd hh:mm"));
	var now_date = new Date();

	Date.prototype.Format = function (fmt,date_num) { //author: meizz
		this.setDate(this.getDate()-date_num);
		var o = {
			"M+": this.getMonth() + 1, //月份
			"d+": this.getDate(), //日
			"H+": this.getHours(), //小时
			"m+": this.getMinutes(), //分
			"s+": this.getSeconds(), //秒
			"q+": Math.floor((this.getMonth() + 3) / 3), //季度
			"S": this.getMilliseconds() //毫秒
		};
		if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
		for (var k in o)
			if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		return fmt;
	};
	// var now_time =  new Date().Format("yyyy-MM-dd HH:mm:ss",0);//当前日期
	var now_time =  new Date().Format("yyyy-MM-dd 23:59:59",0);//当前日期
	var before_time =  new Date().Format("yyyy-MM-dd 00:00:00",date_num-1);//前几天日期
	$("input[name=start_time]").val(before_time,0);
	$("input[name=end_time]").val(now_time,date_num-1);

}

function setArea(sku_id, obj) {
	open('商品区域报价', ns.url('/shop/goods/set_area?sku_id=' + sku_id), '1220px', '660px', true);
}

function open(title, url, width, height, isResize) {
	isResize = isResize === undefined ? true : isResize;
	var index = layer.open({
		title: title,
		type: 2,
		area: [width, height],
		content: url,
		maxmin: true,
		moveOut: true,
		success: function (layero, index) {
			var body = layer.getChildFrame('body', index);
			if (body.length > 0) {
				$.each(body, function (i, v) {
					// todo 优化弹出层背景色修改
					$(v).before('<style>\n' +
						'html, body {\n' +
						'    background: #ffffff;\n' +
						'}\n' +
						'</style>');
				});
			}
		},
		end: function () {
			index = null;
		}
	});
	if (width === undefined || height === undefined) {
		layer.full(index);
	}
	if (isResize) {
		$(window).on("resize", function () {
			index && layer.full(index);
		})
	}
}


